package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.system.dao.ShareUrlMapper;
import com.qinglei.recoup.system.domain.ShareUrl;
import com.qinglei.recoup.system.service.ShareUrlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author syp
 */
@Service
@Slf4j
public class ShareUrlServiceImpl extends ServiceImpl<ShareUrlMapper, ShareUrl> implements ShareUrlService {

    @Override
    public boolean add(ShareUrl shareUrl) {
        String urlFormat = shareUrl.getUrl();
        while (true) {
            String code = RandomStringUtils.randomAlphanumeric(6);
            shareUrl.setCode(code);
            String encCode = Base64.getEncoder().encodeToString(code.getBytes(StandardCharsets.UTF_8));
            String url = String.format(urlFormat, encCode);
            shareUrl.setUrl(url);
            try {
                this.baseMapper.insert(shareUrl);
                return true;
            } catch (DuplicateKeyException e){
                log.warn("add shareUrl duplicate code:{}", code,  e);
            } catch (Exception e) {
                log.error("add shareUrl error", e);
                break;
            }
        }
        return false;
    }
}
